﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Cofe.Core;
using Cofe.Core.Implements;
using Cofe.Core.Utils;
using Cofe.Web.Utils;

namespace Cofe.Web.Controllers.Api
{
    public class SearchController : ApiController
    {
        // GET api/search
        [Authorize]
        [HttpGet]
        public async Task<HttpResponseMessage> SearchAsync(string filterStr, string page = null)
        {
            if (!(String.IsNullOrEmpty(filterStr)))
            {
                if (page != null)
                    filterStr += " page:" + page;

                ParameterDic pd = new ParameterDic();
                var el = await EntryFE.SearchAsync(filterStr, false);
                await el.SearchAsync(pd);

                var r = new WebEntryList() { 
                    Entries = (await el.GetCofeSystemInfosAsync()).Select(e => e as CofeSystemInfo) };

                r.Parameters = pd;
                r.Parameters.Add("out_FilterStr", filterStr);

                var webResourceAttrib = AttributeUtils<WebResourceAttribute>.FindAttribute(CofeDirectoryProperties.List);
                return CofeWsServices.HttpMessageFormatter.CreateResponse(Request, r, r.Parameters, new ResponseFormatterInfo()
                {
                    StatusCode = HttpStatusCode.OK,
                    ResourceAttribute = webResourceAttrib
                });
            }
            return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
        }

        //[Authorize]
        //[HttpPost]
        //public Task<HttpResponseMessage> SearchUsingPostAsync(string filterStr)
        //{
        //    return SearchAsync(filterStr);
        //}

    }
}
